import React, { useEffect, useState, useMemo, useRef } from 'react';
import { Form, Button, Modal, Table } from 'antd';
import { withRouter } from 'umi';
import moment from 'moment';
import { formatSecond } from '@/utils/utils';
import AutoRenderComponent from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/AutoRenderComponent';
import { getLeaveTypeList, getLeaveList } from './services';

import styles from './styles.less';

/**
 * 选择销假组件
 */
const VacationComponent = ({ vacation = {}, onVacationChanged, onChange, config, location, value }) => {
    const { query = {} } = location || {};

    const columns = [
        {
            title: '请假类型',
            dataIndex: 'leaveName'
        },
        {
            title: '开始时间',
            dataIndex: 'startTime'
        },
        {
            title: '结束时间',
            dataIndex: 'endTime'
        },
        {
            title: '请假时长',
            dataIndex: 'leaveLong',
            render: time => <span>{`${time / 60} 小时`}</span>
        },
        {
            title: '请假状态',
            dataIndex: 'leaveStatusName',
            render: text => <span>{text.replace('请假-', '')}</span>
        }
    ];

    const [visibleModal, setVisibleModal] = useState(false);
    const [vacationList, setVacationList] = useState([]);

    const { applicationLeaveNo = '', leaveTypeName = '' } = vacation;
    const { disabled = true } = config.options || {};

    const handleOpenModal = () => {
        if (disabled) {
            return;
        }
        setVisibleModal(true);
    };

    const handleCloseModal = () => {
        setVisibleModal(false);
    };

    const handleSelected = (selectedKey, selectedRow) => {
        if (onVacationChanged) {
            const renameVacation = {
                ...selectedRow[0],
                ...{
                    applicationLeaveNo: selectedRow[0].applicationNo,
                    leaveTypeName: selectedRow[0].leaveName,
                    leaveType: selectedRow[0].leaveCode
                }
            };
            onVacationChanged(renameVacation);
        }

        if (onChange) {
            const { leaveName, leaveCode: leaveType, leaveLong } = selectedRow[0];
            onChange({ applicationLeaveNo: selectedKey[0], leaveTypeName: leaveName, leaveType, leaveLong });
        }
        setVisibleModal(false);
    };

    const vacationTitle = useMemo(() => `${leaveTypeName} ${applicationLeaveNo}`, [applicationLeaveNo, leaveTypeName]);

    useEffect(() => {
        // 获取请假列表
        const fetchLeave = async () => {
            const { code, data } = await getLeaveList();
            if (code === 10000 && data) {
                setVacationList(data);
            }
        };
        if (!disabled) {
            fetchLeave();
        }
    }, [disabled]);

    useEffect(() => {
        if (!value) {
            const { applicationNo } = query;
            if (applicationNo) {
                const selected = vacationList.find(l => l.applicationNo === query.applicationNo);
                if (selected) {
                    handleSelected([selected.applicationNo], [selected]);
                }
            }
        }
    }, [query, vacationList, value]);

    return (
        <div className={styles.VacationComponent}>
            <div className={styles.VacationComponentBox}>
                <Button onClick={handleOpenModal} disabled={disabled}>
                    选择
                </Button>
                {applicationLeaveNo && <span className={styles.VacationComponentBoxTitle}>{vacationTitle}</span>}
            </div>
            <Modal
                title="请假记录"
                width={800}
                visible={visibleModal}
                style={{ maxHeight: 100 }}
                onCancel={handleCloseModal}
                footer={null}
                bodyStyle={styles.vacationComponentModal}
            >
                <Table
                    rowKey="applicationNo"
                    rowSelection={{ type: 'radio', selectedRowKeys: [applicationLeaveNo], onChange: handleSelected }}
                    columns={columns}
                    dataSource={vacationList}
                    pagination={false}
                />
            </Modal>
        </div>
    );
};

const VacationComponentRef = React.forwardRef(withRouter(VacationComponent));

/**
 * 销假套件
 */
const VacationCancel = ({ dataSource, form, formValueMap = {} }) => {
    const { getFieldDecorator } = form;
    const { children: list = [] } = dataSource;
    const [leaveTypes, setLeaveTypes] = useState([]);
    const [selectedVacation, setSelectedVacation] = useState({});
    const formRef = useRef(form);

    const handleVacationChanged = selected => {
        setSelectedVacation(selected);
        form.setFieldsValue({ leaveType: selected?.leaveType });
    };

    // 显示时长
    const getDuration = (val, unit) => {
        if (!val) return 0;
        let last = '';
        if (unit === 1 || unit === 2) {
            last = `${val / 60 / 8}天`;
        } else {
            last = formatSecond(val);
        }

        return last;
    };

    useEffect(() => {
        // 获取请假类型用于格式化时间
        const fetchLeaveTypes = async () => {
            const { companyCode } = formValueMap;
            const { code, data } = await getLeaveTypeList(companyCode);
            if (code === 10000 && data) {
                setLeaveTypes(data);
            }
        };

        fetchLeaveTypes();
    }, []);

    useEffect(() => {
        const { children = [] } = dataSource;
        const [startTime = {}, endTime = {}, vacationSelect = {}] = [
            children.find(item => item.formId === 'startTime'),
            children.find(item => item.formId === 'endTime'),
            children.find(item => item.formId === 'vacationSelect')
        ];
        if (vacationSelect.initialValue) {
            const { leaveType, leaveTypeName, applicationLeaveNo, leaveLong } = vacationSelect.initialValue;
            setSelectedVacation({
                applicationLeaveNo,
                leaveTypeName,
                leaveType,
                startTime: startTime.initialValue,
                endTime: endTime.initialValue,
                leaveLong
            });
        }
    }, [dataSource]);

    useEffect(() => {
        const { startTime, endTime, applicationLeaveNo, leaveLong } = selectedVacation;
        // 获取时间单位
        const getLeaveTimeUnit = () => {
            const { leaveCode } = selectedVacation;
            const { leaveUnit = 3 } = leaveTypes.find(l => l.leaveCode === leaveCode) || {};
            return leaveUnit;
        };

        if (applicationLeaveNo) {
            const unit = getLeaveTimeUnit();
            formRef.current.setFieldsValue({
                startTime: moment(startTime),
                endTime: moment(endTime),
                duration: {
                    durationText: getDuration(leaveLong, unit),
                    duration: leaveLong
                }
            });
        }
    }, [leaveTypes, selectedVacation]);

    return (
        Array.isArray(list) &&
        list.map(item => {
            const { label, formId, rules, initialValue, extra, options } = item;

            if (item.tag === 'VacationButton') {
                return !options.hidden ? (
                    <Form.Item label={label} key={formId} extra={extra}>
                        {getFieldDecorator(formId, {
                            initialValue,
                            rules
                        })(
                            <VacationComponentRef
                                vacation={selectedVacation}
                                onVacationChanged={handleVacationChanged}
                                form={form}
                                config={item}
                            />
                        )}
                    </Form.Item>
                ) : null;
            }

            if (formId === 'leaveType') {
                return (
                    <Form.Item style={{ display: 'none' }} label={label} key={formId} extra={extra}>
                        {getFieldDecorator(formId, {
                            initialValue,
                            rules
                        })(<AutoRenderComponent form={form} config={item} />)}
                    </Form.Item>
                );
            }

            if (item.tag !== 'VacationButton' && selectedVacation.applicationLeaveNo) {
                return (
                    <Form.Item label={label} key={formId} extra={extra}>
                        {getFieldDecorator(formId, {
                            initialValue,
                            rules
                        })(<AutoRenderComponent form={form} config={item} />)}
                    </Form.Item>
                );
            }

            return null;
        })
    );
};

export default VacationCancel;
